package ntu.metaweb.storage;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import ntu.metaweb.XMLMarshaller;
import ntu.p2p.dht.DHTContent;
import ntu.p2p.dht.DHTContentKey;
import ntu.p2p.past.OverwritableContentHashPastContent;

public class PagesWithTag implements DHTContent {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7976138235590686523L;
	
	private PagesWithTagKey key;
	private String text;
	private HashMap<URL,Tag> pages;
	private HashMap<String,Vector<Tag>> userToPages;
	private HashMap<URL,String> pagesTitle;
	private HashMap<URL,Double> pagesRating;
	
	public PagesWithTag(PagesWithTagKey key, String text) {
		this.key = key;
		this.text = text;
		this.pages = new HashMap<URL, Tag>();
		this.pagesTitle = new HashMap<URL, String>();
		this.pagesRating = new HashMap<URL, Double>();
		this.userToPages = new HashMap<String, Vector<Tag>>();
	}

	public void addPage(URL url, String contributor, String title, double rating) {
		if (!pages.containsKey(url)) {
			pages.put(url, new Tag(this.text, url));
		}
		pages.get(url).addContributor(contributor);
		pagesTitle.put(url, title);
		pagesRating.put(url, rating);
		
		if (!this.userToPages.containsKey(contributor)) {
			this.userToPages.put(contributor, new Vector<Tag>());
		}
		this.userToPages.get(contributor).add(pages.get(url));
	}
	
	public String getTag() {
		return this.text;
	}
	
	public Iterator<Tag> getPagesTag() {
		return this.pages.values().iterator();
	}
	
	public void updateTitle(URL url, String title) {
		this.pagesTitle.put(url, title);
	}
	
	public String getPageTitle(URL url) {
		return this.pagesTitle.get(url);
	}
	
	@Override
	public int hashCode() {
		return this.text.hashCode();
	}
	
	@Override
	public boolean equals(Object o) {
		if (!(o instanceof PagesWithTag)) {
			return false;
		}
		
		PagesWithTag pagesWithTag = (PagesWithTag) o;
		return this.text.equals(pagesWithTag.text);
	}

	@Override
	public DHTContentKey getKey() {
		return this.key;
	}

	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		String temp = XMLMarshaller.getInstance().marshall(this);
		buf.writeInt(temp.length());
		buf.write(temp.getBytes(), 0, temp.length());
	}

	public void updateTagRating(URL url, String user, boolean up) {
		this.pages.get(url).addRating(user, up ? 1 : -1);
	}

	public void updatePageRating(URL url, double averageRating) {
		if (this.pagesRating.containsKey(url)) {
			this.pagesRating.put(url, averageRating);
		}
	}

	public double getRating(URL url) {
		if (this.pagesRating.containsKey(url)) {
			return this.pagesRating.get(url);
		}
		return 0;
	}

	public void deleteTag(URL url, String tagger) {
		if (this.pages.containsKey(url)) {
			this.pages.get(url).contributors.remove(tagger);
		}
	}
}
